<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            padding:0;
            margin:0;
        }
        h2{
            width:500px;
            height:30px;
            text-align: center;
        }
        canvas{
            border:1px solid black;
        }
    </style>
</head>
<body>
    <input type="color" id="color">
    <h2>canvas在线绘图</h2>
    <canvas id="c" width="500" height="500">浏览器不支持</canvas>
    <script>
        var c=document.getElementById("c");
        var ctx=c.getContext("2d");
        var color=document.getElementById("color");
        // mousedown 当鼠标按钮按下时候触发
        // mousemove当鼠标按住移动的时候触发
        // mouseup当释放鼠标按钮时候触发
        // clientX鼠标指针相对于窗口的x坐标
        // clientY鼠标指针相对于窗口的y坐标
        // offsetLeft 某个元素距离浏览器左边边缘的位置
        // offsetTop某个元素距离浏览器顶部边缘的位置
        c.onmousedown=function(e){//事件对象
            // console.log(e);
            // console.log(c.offsetLeft);
            // console.log(c.offsetTop);

            var x=e.clientX-c.offsetLeft;
            var y=e.clientY-c.offsetTop;
            ctx.beginPath();
            ctx.moveTo(x,y);
            ctx.lineWitdh=10;
            ctx.lineJoin="round";
            ctx.lineCap="round";
            ctx.strokeStyle=color.value;//获取颜色拾取器的值
            c.onmousemove=function(e2){
                var m=e2.clientX-c.offsetLeft;
                var n=e2.clientY-c.offsetTop;
                ctx.lineTo(m,n);
                ctx.stroke();
            };



        };
        c.onmouseup=function(){
            c.onmousemove=null;
        };

    </script>
</body>
</html>